<template>
  <div class="tab-container waybill-tab-container abroadWaybillEdit">
    <div class="header-info">
      <div class="flex align-center">
        <div class="margin-right">
          <div style="font-size:16px;">
            {{ waybillInfo.waybillNo }}
          </div>
          <div>操作批次{{ waybillInfo.returnBatchIndex }}</div>
        </div>
        <div class="margin-right">
          <div>
            销售:
            {{
              initData.userMap ? initData.userMap[waybillInfo.salesmanId] : ""
            }}
          </div>
          <div>
            客服:
            {{
              initData.userMap ? initData.userMap[waybillInfo.servicesId] : ""
            }}
          </div>
        </div>
        <div class="flex align-center">
          <el-tooltip class="item" effect="light" placement="left">
            <div slot="content" v-html="waybillInfo.customerRemark"></div>
            <i class="el-icon-s-custom text-xl margin-right-sm"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="light" placement="left">
            <div slot="content" v-html="waybillInfo.sysRemark"></div>
            <i class="el-icon-chat-dot-round text-xl margin-right-sm"></i>
          </el-tooltip>

          <span class="margin-right-sm">
            <el-tooltip effect="light" content="海外仓账单" placement="top">
              <img
                v-if="yesBillStatusBackImg"
                :src="
                  waybillInfo.billStatus == 1
                    ? yesBillStatusBackImg
                    : noBillStatusBackImg
                "
              />
            </el-tooltip>
          </span>
          <span class="margin-right-sm">
            <el-popover placement="bottom" trigger="hover">
              <div
                v-if="waybillInfo.orderLocked"
                class="pointer margin-sm"
                @click="lockWaybill"
              >
                解锁
              </div>
              <div v-else class="pointer margin-sm" @click="lockWaybill">
                锁单
              </div>
              <div class="pointer margin-sm" @click="generateBill">
                生成海外仓账单
              </div>
              <div
                v-if="verifyShow.exportEdit"
                class="pointer margin-sm"
                @click="exportWaybill"
              >
                导出运单账单
              </div>
              <div
                class="pointer margin-sm"
                @click="dialogModifyTrackingNum = true"
              >
                修改跟踪号
              </div>
              <div
                v-if="waybillInfo.status === 20"
                class="pointer margin-sm"
                @click="replyAbroadWaybill"
              >
                打回待确认
              </div>
              <span slot="reference" class="text-blue text-df">编辑</span>
            </el-popover>
          </span>
        </div>
        <div class="pointer" @click="toSeaair(waybillInfo.seaAirWaybillNo)">
          {{ waybillInfo.seaAirWaybillNo }}
        </div>
      </div>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="运单编辑" name="edit">
        <div class="padding">
          <!-- <el-button @click="toPage">toPage</el-button> -->
          <ProgressBar
            :verifyShow="verifyShow"
            ref="bar"
            :isEdit="isEdit"
            :isAbroad="true"
            :progressList="progress"
            :waybillInfo="waybillInfo"
            @saveStateLine="saveStateLine"
          ></ProgressBar>
          <BasicInfo
            v-if="verifyShow.waybInfo"
            :verifyShow="verifyShow"
            :isEdit="isEdit"
            :countryMap="initData.countryMap"
            :customerAll="initData.customerMap"
            :customerPermissionsMap="initData.customerPermissionsMap"
            :customerCodeMap="initData.customerCodeMap"
            :serviceItemMap="initData.serviceItemMap"
            :waybillInfo="waybillInfo"
            :abroadStockAddressSource="initData.abroadStockAddressMap"
          ></BasicInfo>

          <CargoInfo
            :verifyShow="verifyShow"
            :isEdit="isEdit"
            :goodsInfo.sync="goodsInfo"
            :oldGoodsInfo="oldGoodsInfo"
            :waybillId="waybillId"
          ></CargoInfo>

          <InventorySummary
            :verifyShow="verifyShow"
            :isEdit="isEdit"
            :inStockInfo="inStockInfo"
            :waybillId="waybillId"
          ></InventorySummary>

          <WarehouseRecord
            :verifyShow="verifyShow"
            :isEdit="isEdit"
            :stockCostInfo="stockCostInfo"
            :initTableData="initData"
            :waybillId="waybillId"
          ></WarehouseRecord>

          <ReturnInfo
            v-if="verifyShow.returnInfo"
            :verifyShow="verifyShow"
            :isEdit="isEdit"
            :returnTrackingInfo.sync="returnTrackingInfo"
            :oldReturnTrackingInfo="oldReturnTrackingInfo"
            :waybillId="waybillId"
            :returnBatchIndex="Number(waybillInfo.returnBatchIndex)"
            @getReturnInfo="getReturnInfo"
            @getOperation="getOperation"
          ></ReturnInfo>
          <OperationInstructionInfo
            :verifyShow="verifyShow"
            :isEdit="isEdit"
            :OperationInstructionData.sync="OperationInstructionData"
            :oldOperationInstructionData="oldOperationInstructionData"
            :waybillId="waybillId"
          ></OperationInstructionInfo>
          <PackingListInfo
            v-if="verifyShow.invoiceView"
            :verifyShow="verifyShow"
            :isEdit="isEdit"
            :packingList.sync="packingList"
            :waybillId="waybillId"
            @getPacking="getPacking"
          ></PackingListInfo>
          <DeliveryInfo
            v-if="verifyShow.returnInfo"
            :verifyShow="verifyShow"
            :isEdit="isEdit"
            :shipmentTrackingInfo.sync="shipmentTrackingInfo"
            :oldShipmentTrackingInfo.sync="oldShipmentTrackingInfo"
            :waybillId="waybillId"
            :shippingfbastockMap="initData.fbaCodeList"
          ></DeliveryInfo>
        </div>
      </el-tab-pane>
      <el-tab-pane label="文件列表" name="fileList" lazy>
        <FileList
          v-if="verifyShow.fileView"
          :verifyShow="verifyShow"
          :activeName="activeName"
          :waybillId="waybillId"
          :fileTypeMap="initData.fileTypeMap"
          :userAll="initData.userMap"
          :shippingWay="waybillInfo.shippingWay"
        ></FileList>
      </el-tab-pane>
      <el-tab-pane label="应收应付/阿米巴" name="receivable" lazy>
        <Receivable
          v-if="verifyShow.payAndReceView"
          :verifyShow="verifyShow"
          ref="rec"
          :isEdit="isEdit"
          :Constatvariable="waybillInfo"
          :initTableData="initData"
        ></Receivable>

        <Amoeba
          :verifyShow="verifyShow"
          ref="amb"
          :isEdit="isEdit"
          :Constatvariable="waybillInfo"
          :initTableData="initData"
          @updateToReceive="updateReceive"
        />
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      title="修改跟踪号"
      :visible.sync="dialogModifyTrackingNum"
      width="30%"
    >
      <el-form label-width="80px" size="mini" :model="waybillInfo">
        <el-form-item label="跟踪号1">
          <el-input v-model="waybillInfo.trackNumber1"></el-input>
        </el-form-item>
        <el-form-item label="跟踪号2">
          <el-input v-model="waybillInfo.trackNumber2"></el-input>
        </el-form-item>
        <el-form-item label="跟踪号3">
          <el-input v-model="waybillInfo.trackNumber3"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogModifyTrackingNum = false"
          >取 消</el-button
        >
        <el-button size="mini" type="primary" @click="modifyTrackingNum"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import yesBillStatusBackPng from "@/assets/images/yes_bill_status_back.png";
import noBillStatusBackPng from "@/assets/images/no_bill_status_back.png";

import ProgressBar from "@/components/app/components/ProgressBar";
import InventorySummary from "./components/InventorySummary";
import BasicInfo from "./components/BasicInfo";
import CargoInfo from "./components/CargoInfo";
import ReturnInfo from "./components/ReturnInfo";
import FileList from "./components/FileList";
import PackingListInfo from "./components/PackingListInfo";
import DeliveryInfo from "./components/DeliveryInfo";
import Receivable from "./components/Receivable";
import WarehouseRecord from "./components/WarehouseRecord";
import OperationInstructionInfo from "./components/OperationInstructionInfo";
import Amoeba from "./components/Amoeba";
import { ajax, getQueryVariable } from "@/store/yg/common/utils";
import { clone } from "@/utils/clone";
import globalData from "@/utils/config";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
import MiddleUtil from "@/utils/MiddleUtil";
export default {
  components: {
    ProgressBar,
    InventorySummary,
    WarehouseRecord,
    ReturnInfo,
    BasicInfo,
    CargoInfo,
    FileList,
    OperationInstructionInfo,
    PackingListInfo,
    DeliveryInfo,
    Receivable,
    Amoeba
  },
  props: ["data"],
  data() {
    return {
      dialogModifyTrackingNum: false,
      yesBillStatusBackImg: yesBillStatusBackPng,
      noBillStatusBackImg: noBillStatusBackPng,
      abroadStockAddressSource: {},
      servcerParse: "",
      isEdit: true,
      progress: [],
      activeName: "edit",
      waybillId: 1,
      initData: {},
      initTableData: {
        //账单类型
        options: ["起", "目"]
      },
      waybillInfo: {},
      goodsInfo: [],
      returnTrackingInfo: [],
      packingList: [],
      OperationInstructionData: [],
      shipmentTrackingInfo: [],
      oldGoodsInfo: [],
      oldShipmentTrackingInfo: [],
      oldOperationInstructionData: [],
      oldReturnTrackingInfo: [],
      inStockInfo: [],
      stockCostInfo: [],
      attrs: {
        class: "com.tofba.app.client.abroad.AbroadWaybillClient",
        uri: "/open/message",
        type: "blank"
      },
      verifyShow: {}
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.waybillId = Number(getQueryVariable("pid"));
    this.init();
    let tabName = sessionStorage.getItem("abroadTab");
    //判断是否存在currentTab,即tab页之前是否被点击切换到别的页面
    if (tabName) {
      this.activeName = tabName;
    }
  },
  destroyed() {
    sessionStorage.removeItem("abroadTab");
  },
  methods: {
    updateReceive() {
      if (this.$refs.rec) {
        this.$refs.rec.getPaymentReceivable();
      }
    },
    handleClick(tab) {
      // 点击tab后触发事件，修改显示页面
      sessionStorage.setItem("abroadTab", tab.name);
    },
    async saveStateLine(params) {
      params.id = this.waybillInfo.id;
      const data = await ajax("saveAbroadWaybillStateLine", params);

      if (data.code === 200) {
        this.$message({
          message: "提交成功",
          type: "success"
        });
      } else {
        this.$message.error(data.message);
      }
      this.getProgress();
      this.getWaybillInfo();
      this.$refs.bar.changeDialog = false;
    },
    handleClick(val) {
      console.log(val);
    },
    async init() {
      // servcerParseSource
      this.getProgress();
      // 运单信息
      ajax("abroadEditVerifyPermissions", {})
        .then(res => {
          this.verifyShow = res;
        })
        .catch();
      ajax("initAbroadWaybillRender", {}).then(res => {
        // if (res.code === 200) {
        this.initData = res.data;
        this.initData.options = ["起", "目"];
        this.initData.userOptions = this.getVal(this.initData.userMap);
        this.initData.currencyOptions = this.getVal(this.initData.currencyMap);
        this.initData.serviceOptions = this.getVal(
          this.initData.serveCompanyMap
        );
        this.initData.companyOptions = this.getVal(this.initData.customerMap);
        this.initData.configPayNameOptions = this.getVal(
          this.initData.payNameMap
        );
        this.initData.userDeparOptions = this.getVal(
          this.initData.userDeparMap
        );
        this.initData.amoebaSubjectOptions = this.getVal(
          this.initData.amoebaSubjectMap
        );
        const arr = [];
        for (const i in this.initData.shippingfbastockMap) {
          arr.push(i);
        }
        // console.log("arr :>> ", arr);
        this.initData.fbaCodeList = arr;
        // console.log("this.initData :>> ", this.initData);
        // }
      });

      this.getWaybillInfo();
      this.abroadStockAddressSource = await this.getSource(
        "abroadStockAddressSource"
      );

      // 货物信息
      ajax("getGoodsInfoByWaybillId", {
        id: this.waybillId
      }).then(res => {
        if (res.code === 200) {
          if (res.data.length === 0) {
            this.goodsInfo = [{}];
            this.oldGoodsInfo = [{}];
          } else {
            this.goodsInfo = res.data;
            this.oldGoodsInfo = clone(res.data);
          }
        }
      });
      // 库存信息
      ajax("getAbroadStockGoodsWaybillId", {
        waybillId: Number(this.waybillId)
      }).then(res => {
        console.log("getAbroadStockGoodsWaybillId :>> ", res);
        if (res) {
          this.inStockInfo = res;
        }
      });
      // 仓租结算记录
      ajax("queryAbroadStockCostInfo", {
        waybillId: Number(this.waybillId)
      }).then(res => {
        console.log("queryAbroadStockCostInfo :>> ", res);
        if (res) {
          this.setStockCostInfo(res);
        }
      });

      this.getPacking();
      this.getReturnInfo();
      this.getOperation();

      // 发货追踪信息T
      ajax("queryAbroadTrackAddresslist", {
        id: this.waybillId
      }).then(res => {
        if (res.code === 200) {
          if (res.data.length === 0) {
            this.shipmentTrackingInfo = [{}];
            this.oldShipmentTrackingInfo = [{}];
          } else {
            this.shipmentTrackingInfo = res.data;
            this.oldShipmentTrackingInfo = clone(res.data);
          }
        }
      });
    },
    setStockCostInfo(res) {
      if (this.initData.customerMap) {
        for (const i of res) {
          i.customerId = this.initData.customerMap[i.customerId];
          i.costName = this.initData.payNameMap[i.costName];
        }
        this.stockCostInfo = res;
      } else {
        setTimeout(() => {
          this.setStockCostInfo(res);
        }, 1000);
      }
    },
    replyAbroadWaybill() {
      this.$confirm("此操作将打回待确认,是否继续？").then(_ => {
        ajax("replyAbroadWaybill", { id: this.waybillId }).then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            console.log(res);
          } else {
            this.$message.error("系统内部异常");
          }
        });
      });
    },
    getWaybillInfo() {
      ajax("getAbroadWaybill", {
        id: this.waybillId
      }).then(waybillInfo => {
        if (waybillInfo.code === 500) {
          this.$message.error(waybillInfo.message || "获取运单信息失败！");
          if (waybillInfo.message.indexOf("权限") > -1) {
            window.open("/", "_self");
          }

          return;
        }
        waybillInfo.serviceItemArr = waybillInfo.serviceItem.split(",");
        this.waybillInfo = waybillInfo;
        document.title = waybillInfo.waybillNo;
        if (this.waybillInfo.orderLocked) {
          this.isEdit = false;
        } else {
          this.isEdit = true;
        }
      });
    },
    getProgress() {
      ajax("initAbroadWaybillState", { id: this.waybillId }).then(res => {
        if (res.code === 200) {
          this.progress = res.data;
        }
      });
    },
    getOperation() {
      // 操作指令
      ajax("queryAbroadOperationByWaybillId", {
        id: this.waybillId
      }).then(res => {
        if (res.code === 200) {
          if (res.data.length === 0) {
            this.OperationInstructionData = [{}];
            this.oldOperationInstructionData = [{}];
          } else {
            this.OperationInstructionData = res.data;
            this.oldOperationInstructionData = clone(res.data);
          }
        }
      });
    },
    getReturnInfo() {
      // 退货追踪信息
      ajax("queryAbroadReturnReceiveGoodsByWaybillId", {
        id: this.waybillId
      }).then(res => {
        if (res.code === 200) {
          const arr = [];
          for (const i of res.data) {
            if (i.abroadSkuList) {
              for (const j of i.abroadSkuList) {
                arr.push({
                  id: i.id,
                  trackNo: i.trackNo,
                  returnNo: i.returnNo,
                  shipmentId: i.shipmentId,
                  cartons: i.cartons,
                  sortNo: i.sortNo,
                  sku: j.sku,
                  skuId: j.id,
                  num: j.num,
                  receiptDate: i.receiptDate,
                  receiptPallets: i.receiptPallets,
                  receiptQuantity: j.receiptQuantity,
                  receiptCartons: i.receiptCartons,
                  boxSpecifications: i.boxSpecifications,
                  location: j.location,
                  receiptCondition: j.receiptCondition
                });
              }
            } else {
              arr.push(i);
            }
          }
          if (arr.length === 0) {
            this.returnTrackingInfo = [{}];
            this.oldReturnTrackingInfo = [{}];
          } else {
            this.returnTrackingInfo = arr;
            this.oldReturnTrackingInfo = clone(arr);
          }
        }
      });
    },
    getPacking() {
      // 箱单信息
      ajax("queryAbroadPackingByWaybillId", {
        id: this.waybillId
      }).then(res => {
        if (res.code === 200) {
          if (res.data.length === 0) {
            this.packingList = [{}];
          } else {
            this.packingList = res.data;
          }
        }
      });
    },

    getVal(map) {
      const arr = [];
      for (const i in map) {
        arr.push(map[i]);
      }
      return arr;
    },
    async getSource(name) {
      const uri = "/api/entry/source?bean=" + name;
      const { data } = await axios.post(constant.API_SERVER + uri);
      return data;
    },
    async modifyTrackingNum() {
      // updateTrackNumber
      const params = {
        id: this.waybillInfo.id,
        trackNumber1: this.waybillInfo.trackNumber1,
        trackNumber2: this.waybillInfo.trackNumber2,
        trackNumber3: this.waybillInfo.trackNumber3
      };
      const { code } = await ajax("updateTrackNumber", params, this.attrs);
      if (code === 200) {
        this.$message.success("修改跟踪号成功！");
        this.dialogModifyTrackingNum = false;
      } else {
        this.$message.error("修改跟踪号失败！");
      }
    },
    async exportWaybill() {
      //const id = this.waybillInfo.id;
      const data = await ajax(
        "exportAbroadWaybillBillToPdf",
        this.waybillInfo,
        this.attrs
      );
      if (data.path) {
        window.open(constant.FILE_SERVER + data.path);
      } else {
        this.$message.error("导出错误");
      }
    },
    async generateBill() {
      const id = this.waybillInfo.id;
      const { code } = await ajax("updateAbroadBillStatus", { id }, this.attrs);
      if (code === 200) {
        this.$message.success("生成海外仓账单成功！");
      } else {
        this.$message.error("生成海外仓账单失败！");
      }
    },
    async lockWaybill() {
      if (this.waybillInfo.orderLocked) {
        const { code } = await ajax(
          "updateUnlockingAbroadWaybill",
          [this.waybillInfo.id],
          this.attrs
        );
        if (code === 200) {
          this.$message.success("订单解锁成功！");
          this.getWaybillInfo();
        } else {
          this.$message.error("订单解锁失败！");
        }
      } else {
        const { code } = await ajax(
          "updateIslockAbroadWaybill",
          [this.waybillInfo.id],
          this.attrs
        );
        if (code === 200) {
          this.$message.success("订单锁单成功！");
          this.getWaybillInfo();
        } else {
          this.$message.error("订单锁单失败！");
        }
      }
    },
    async toSeaair(no) {
      MiddleUtil.$emit("toSearch", no);
    }
  }
};
</script>
<style lang="scss" scoped>
.title-icon {
  display: inline-block;
  width: 120px;
}
</style>

<style scoped>
/deep/ .el-tabs__item.is-disabled {
  color: #51abd1;
}

/deep/ .el-tabs__header {
  position: fixed;
  top: 26px;
  /* width: 92%; */
  z-index: 12;
  background: #fff;
}

.header-info {
  position: fixed;
  z-index: 12;
  top: 16px;
  left: 470px;
}

img {
  display: block;
}
</style>
